﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

namespace btnet
{
    public class Global : System.Web.HttpApplication
    {
        string prev_day = DateTime.Now.ToString("yyyy-MM-dd");

        protected void Application_Error(Object sender, EventArgs e)
        {

            StringBuilder server_vars = new StringBuilder();

            int loop1, loop2;
            NameValueCollection coll;

            // Load ServerVariable collection into NameValueCollection object.
            coll = Request.ServerVariables;
            // Get names of all keys into a string array.
            String[] arr1 = coll.AllKeys;
            for (loop1 = 0; loop1 < arr1.Length; loop1++)
            {
                server_vars.Append("\n");
                server_vars.Append(arr1[loop1]);
                server_vars.Append("=");
                String[] arr2 = coll.GetValues(arr1[loop1]);
                for (loop2 = 0; loop2 < 1; loop2++)
                {
                    server_vars.Append(arr2[loop2]);
                }
            }


            Exception exc = Server.GetLastError().GetBaseException();

            bool log_enabled = (Bug_Util.get_setting("LogEnabled", "1") == "1");
            if (log_enabled)
            {

                string path = Bug_Util.get_log_file_path();

                // open file
                StreamWriter w = File.AppendText(path);

                w.WriteLine("\nTIME: " + DateTime.Now.ToLongTimeString());
                w.WriteLine("MSG: " + exc.Message.ToString());
                w.WriteLine("URL: " + Request.Url.ToString());
                w.WriteLine("EXCEPTION: " + exc.ToString());
                w.WriteLine(server_vars.ToString());
                w.Close();
            }

            bool error_email_enabled = (Bug_Util.get_setting("ErrorEmailEnabled", "1") == "1");
            if (error_email_enabled)
            {

                if (exc.Message.ToString() == "Expected integer.  Possible SQL injection attempt?")
                {
                    // don't bother sending email.  Too many automated attackers
                }
                else
                {
                    string to = Bug_Util.get_setting("ErrorEmailTo", "");
                    string from = Bug_Util.get_setting("ErrorEmailFrom", "");
                    string subject = "Error: " + exc.Message.ToString();

                    StringBuilder body = new StringBuilder();

                    body.Append("\nTIME: ");
                    body.Append(DateTime.Now.ToLongTimeString());
                    body.Append("\nURL: ");
                    body.Append(Request.Url.ToString());
                    body.Append("\nException: ");
                    body.Append(exc.ToString());
                    body.Append(server_vars.ToString());

                    btnet.Email.send_email(to, from, "", subject, body.ToString()); // 5 args				
                }
            }
        }

        protected void Application_Start(object sender, EventArgs e)
        {
            string path = HttpContext.Current.Server.MapPath(null);

            string dir = path + "\\App_Data";
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            dir = path + "\\App_Data\\logs";
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            dir = path + "\\App_Data\\uploads";
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            dir = path + "\\App_Data\\lucene_index";
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            Bug_Util.set_context(HttpContext.Current); // required for map path calls to work in Bug_Util.cs

            StreamReader sr = File.OpenText(path + "\\custom\\custom_header.html");
            Application["custom_header"] = sr.ReadToEnd();
            sr.Close();

            sr = File.OpenText(path + "\\custom\\custom_footer.html");
            Application["custom_footer"] = sr.ReadToEnd();
            sr.Close();

            sr = File.OpenText(path + "\\custom\\custom_logo.html");
            Application["custom_logo"] = sr.ReadToEnd();
            sr.Close();

            sr = File.OpenText(path + "\\custom\\custom_welcome.html");
            Application["custom_welcome"] = sr.ReadToEnd();
            sr.Close();


            if (Bug_Util.get_setting("EnableTags", "0") == "1")
            {
                Tags.build_tag_index(this.Application);
            }


            if (Bug_Util.get_setting("EnableLucene", "1") == "1")
            {
                MyLucene.build_lucene_index(this.Application);
            }
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}